# coding=utf-8
# coding=utf-8
import json
from abc import ABCMeta

import tornado.web

import WrapCursor
from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.TimingSwitch import TimingSwitch


class UpdTimingSwitch(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        print(self.request.body)
        ojson = None
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            data = ojson['desc']
            data = ojson['opt']
            _ = ojson['PointID']
            data = ojson['params']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error('request data error' + str(e.message)))
            return

        def check_time_type(ojson2, keystr):
            """
            :param keystr:
            :param ojson2:
            :type ojson2: object
            """
            if keystr not in ojson2:
                o = {'enable': False}
                ojson[keystr] = o

        check_time_type(ojson, 'WallTime')
        check_time_type(ojson, 'DayTime')
        check_time_type(ojson, 'Weekday')
        check_time_type(ojson, 'SunUpLightOff')
        check_time_type(ojson, 'SunUpLightOn')
        check_time_type(ojson, 'SunDownLightOff')
        check_time_type(ojson, 'SunDownLightOn')
        if 'Location' not in ojson:
            location = dict()
            location['longitude'] = 116.388
            location['latitude'] = 39.91
            ojson['Location'] = location

        desc = ojson['desc']
        Opt = 4  # ojson['opt']
        Params = ojson['params']
        isRunning = 0

        def getTime(key, content, func, runf=1):
            if runf == 1 and ojson[key]['enable']:
                return ojson[key][content]
            else:
                if func is int:
                    return 0
                return func("")

        desc = desc
        Opt = Opt
        Params = Params
        PointID = ojson['PointID']
        isRunning = 0
        WallTime = getTime('WallTime', 'timepoint', str)
        daytime = getTime('DayTime', 'daytime', str)
        weekday = getTime('Weekday', 'weekday', list)
        sunup_lightoff = 1 if ojson['SunUpLightOff']['enable'] else 0
        sunup_lightoff_delay_seconds = getTime('SunUpLightOff', 'delay_seconds', int, sunup_lightoff)
        sunup_lighton = 1 if ojson['SunUpLightOn']['enable'] else 0
        sunup_lighton_delay_seconds = getTime('SunUpLightOn', 'delay_seconds', int, sunup_lighton)
        sundown_lighton = 1 if ojson['SunDownLightOn']['enable'] else 0
        sundown_lighton_delay_seconds = getTime('SunDownLightOn', 'delay_seconds', int, sundown_lighton)
        sundown_lightoff = 1 if ojson['SunDownLightOff']['enable'] else 0
        sundown_lightoff_delay_seconds = getTime('SunDownLightOff', 'delay_seconds', int, sundown_lightoff)
        longitude = ojson['Location']['longitude']
        Latitude = ojson['Location']['latitude']

        sqlargs = (Opt, Params, PointID, isRunning,
                   WallTime, daytime, str(weekday),
                   sunup_lightoff, sunup_lightoff_delay_seconds,
                   sunup_lighton, sunup_lighton_delay_seconds,
                   sundown_lighton, sundown_lighton_delay_seconds,
                   sundown_lightoff, sundown_lightoff_delay_seconds,
                   longitude, Latitude, desc)

        s = Session()
        tming = s.query(TimingSwitch).filter_by(desc=desc).all()
        if len(tming) is not 1:
            self.write(r.Error(u'失败:未找到定时模式'))
            return
        tming = tming[0]
        tming.OptTypeID = Opt
        tming.Params = Params
        tming.PointID = PointID
        tming.IsRunning = isRunning
        tming.wallTime = WallTime
        tming.everyDay = daytime
        tming.weekDay = str(weekday)
        tming.sunup_lightoff = sunup_lightoff
        tming.sunup_lightoff_delay = sunup_lightoff_delay_seconds
        tming.sunup_lighton = sunup_lighton
        tming.sunup_lighton_delay = sunup_lighton_delay_seconds
        tming.sundown_lightoff = sundown_lightoff
        tming.sundown_lightoff_delay = sundown_lightoff_delay_seconds
        tming.sundown_lighton_delay = sundown_lighton_delay_seconds
        tming.sundown_lighton = sundown_lighton
        try:
            s.commit()
        except Exception as e:
            self.write(r.Error(str(u'失败:更新失败')))
            return
        self.write(r.Ok(u'成功'))
        return
